package com.example.springboot.controller.api;

import com.example.springboot.common.Result;
import com.example.springboot.entity.Reviews;
import com.example.springboot.entity.User;
import com.example.springboot.mapper.ReviewsMapper;
import com.example.springboot.service.IReviewsService;
import com.example.springboot.service.IUserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 评论表 API控制器 - 专门用于不需要token验证的API
 * </p>
 *
 * @author
 */
@RestController
@RequestMapping("/api/reviews")
public class ReviewsApi {
    @Resource
    private IReviewsService iReviewsService;
    @Resource
    private ReviewsMapper reviewsMapper;
    @Resource
    private IUserService iUserService;

    // 新增或者更新
    @PostMapping("/add")
    public Result save(@RequestBody Reviews reviews) {

        iReviewsService.saveOrUpdate(reviews);
        return Result.success();
    }

    /**
     * 获取民宿评论列表
     */
    @GetMapping("/list/{HomestayId}")
    public Result getComments(@PathVariable Integer HomestayId) {
        // 查询所有评论（包括回复）
        List<Reviews> allComments = iReviewsService.lambdaQuery()
                .eq(Reviews::getHomestayId, HomestayId)
                .eq(Reviews::getStatus,1)
                .orderByAsc(Reviews::getTime)
                .list();

        // 查询并设置用户信息
        allComments.forEach(comment -> {
            User user = iUserService.getById(comment.getUserId());
            if (user != null) {
                comment.setUsername(user.getUsername());
                comment.setNickname(user.getNickname());
                comment.setAvatar(user.getAvatarUrl());
            }
        });

        return Result.success(allComments);
    }
}
